package com.leo;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.IntBuffer;

/**
 * @ClassName WritableImageDemo
 * @Description 将一张图片的一半，写入到另一张图片的一半里
 * @Author wangss
 * @date 2020.06.02 21:47
 * @Version 1.0
 */
public class WritableImage2Demo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(an);

        Image image1 = new Image("images/9.jpeg");

        Image image2 = new Image("images/19.jpeg");

        WritableImage writableImage = new WritableImage(image2.getPixelReader(), 1200, 1200);

        WritablePixelFormat<IntBuffer> intArgbPreInstance = PixelFormat.getIntArgbPreInstance();
        int[] in = new int[1200 / 2 * 800];

        // 获取第一张图片一半的像素
        PixelReader pixelReader = image1.getPixelReader();
        pixelReader.getPixels(0, 0, 1200 / 2, 800, intArgbPreInstance, in, 0, 1200 / 2);

        // 将获取到的像素写到第二张图片里
        PixelWriter pixelWriter = writableImage.getPixelWriter();
        pixelWriter.setPixels(0, 0, 1200 / 2, 800, intArgbPreInstance, in, 0, 1200 / 2);
        // 写入的方式二
        /*for (int i = 0; i < 1200 / 2; i++) {
            for (int j = 0; j < 800; j++) {
                Color color = pixelReader.getColor(i, j);
                pixelWriter.setColor(i, j, color);
            }
        }*/

        // 写入方式三
//        pixelWriter.setPixels(0, 0, 1200 / 2, 800, pixelReader, 0, 0);

        ImageView imageView = new ImageView(writableImage);

        an.getChildren().add(imageView);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ImageViewDemo");
        primaryStage.setWidth(600d);
        primaryStage.setHeight(600d);
//        primaryStage.setResizable(false);
        primaryStage.show();

        // 将处理以后的照片写到磁盘上，这里注意：这里处理以后的图片是 32位的，jpg是24位的，所以要用png保存
        BufferedImage bufferedImage = SwingFXUtils.fromFXImage(writableImage, null);
        ImageIO.write(bufferedImage, "png", new File("D:/log/newImage.png"));
    }
}
